package org.luckystrophe.snowtoms.adapter;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;
import org.luckystrophe.snowtoms.R;
import org.luckystrophe.snowtoms.SettingActivity_;
import org.luckystrophe.snowtoms.model.JsonRequest;
import org.luckystrophe.snowtoms.model.SettingChild;
import org.luckystrophe.snowtoms.model.impl.ChildViewInfo;
import org.luckystrophe.snowtoms.model.impl.ChildViewMyPlace;
import org.luckystrophe.snowtoms.model.impl.ChildViewProfile;
import org.luckystrophe.snowtoms.model.impl.LoginPost;
import org.luckystrophe.snowtoms.model.impl.SettingGroup;
import org.luckystrophe.snowtoms.pref.UserPreference_;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.googlecode.androidannotations.annotations.AfterViews;
import com.googlecode.androidannotations.annotations.Background;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.EBean;
import com.googlecode.androidannotations.annotations.RootContext;
import com.googlecode.androidannotations.annotations.SystemService;
import com.googlecode.androidannotations.annotations.UiThread;
import com.googlecode.androidannotations.annotations.res.DrawableRes;
import com.googlecode.androidannotations.annotations.res.StringArrayRes;
import com.googlecode.androidannotations.annotations.res.StringRes;
import com.googlecode.androidannotations.annotations.sharedpreferences.Pref;

@EBean
public class AdapterSettings extends BaseExpandableListAdapter implements OnClickListener {

	private ArrayList<ArrayList<SettingChild>> mChildList;
	private ArrayList<SettingGroup> mGroupList = null;
	private ViewHolder viewHolder = null;

	@SystemService
	public LayoutInflater inflater;

	@DrawableRes
	Drawable profile;

	@DrawableRes
	Drawable alarm;

	@DrawableRes
	Drawable location;

	@DrawableRes
	Drawable copyright;

	@StringRes
	String facebook_login;

	@StringRes
	String facebook_logout;

	@StringRes
	String facebook;

	@StringRes
	String kakao;

	@StringRes
	String alarm_like;

	@StringRes
	String alarm_reply;

	@StringRes
	String company;

	@StringRes
	String my_place;

	@RootContext
	Context context;

	@Pref
	UserPreference_ pref;

	AQuery aq;

	@StringArrayRes(R.array.setLocation)
	String[] gu_locations;

	@Bean(LoginPost.class)
	JsonRequest loginPost;

	Toast pleaseLoginToast = null;

	@AfterViews
	void afterViews() {
		mGroupList = new ArrayList<SettingGroup>();
		mChildList = new ArrayList<ArrayList<SettingChild>>();

		ArrayList<SettingChild> profileChilds = new ArrayList<SettingChild>();
		ArrayList<SettingChild> infoChilds = new ArrayList<SettingChild>();
		ArrayList<SettingChild> myPlace = new ArrayList<SettingChild>();

		mGroupList.add(new SettingGroup("프로필", profile));
		mGroupList.add(new SettingGroup(setGroupLoccationTitle(), location));
		mGroupList.add(new SettingGroup("만든이", copyright));

		String facebookId = pref.collaboId().get();
		String userImage = "https://graph.facebook.com/" + facebookId + "/picture?width=230&height=230";

		profileChilds.add(new ChildViewProfile(pref.name().get(), userImage));

		myPlace.add(new ChildViewMyPlace(pref.location().get()));

		infoChilds.add(new ChildViewInfo("한정환 : 기획자"));
		infoChilds.add(new ChildViewInfo("한대환 : 개발자"));
		infoChilds.add(new ChildViewInfo("윤소연 : UX 디자이너"));
		infoChilds.add(new ChildViewInfo("이정은 : GUI 디자이너"));
		infoChilds.add(new ChildViewInfo("문의 : thinkinghans@naver.com"));

		mChildList.add(profileChilds);
		mChildList.add(myPlace);
		mChildList.add(infoChilds);
		this.notifyDataSetChanged();
	}

	@Override
	public SettingChild getChild(int groupPosition, int childPosition) {
		return mChildList.get(groupPosition).get(childPosition);
	}

	@Override
	public long getChildId(int groupPosition, int childPosition) {
		return childPosition;
	}

	@Override
	public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
			ViewGroup parent) {

		View v = inflater.inflate(getLayout(groupPosition), null);
		aq = new AQuery(v);
		switch (groupPosition) {
		case 0:
			ChildViewProfile profile = (ChildViewProfile) mChildList.get(groupPosition).get(childPosition);
			Bitmap preset = aq.getCachedImage(R.drawable.profile_emptybox);
			aq.id(R.id.iv_child_profile).image(profile.getImageSource(), true, true, 0, R.drawable.profile_emptybox,
					preset, AQuery.FADE_IN_NETWORK);
			aq.id(R.id.tv_child_name).text(profile.getString());
			LoginButton authButton = (LoginButton) v.findViewById(R.id.btn_fblogin);
			authButton.setSessionStatusCallback(new MStatusCallback());
			break;
		case 1:
			aq.id(R.id.btn_setLocation).clicked(this);
			setLocationText(pref.location().get());
			// aq.id(R.id.sp_child_myplace).adapter(
			// ArrayAdapter.createFromResource(context, R.array.seoul,
			// android.R.layout.simple_list_item_1));
			break;
		case 2:
			ChildViewInfo info = (ChildViewInfo) mChildList.get(groupPosition).get(childPosition);
			aq.id(R.id.tv_info).text(info.getString());
			break;

		}
		return v;
	}

	@Override
	public int getChildrenCount(int groupPosition) {
		return mChildList.get(groupPosition).size();
	}

	@Override
	public SettingGroup getGroup(int groupPosition) {
		return mGroupList.get(groupPosition);
	}

	@Override
	public int getGroupCount() {
		return mChildList.size();
	}

	@Override
	public long getGroupId(int groupPosition) {
		return groupPosition;
	}

	@SuppressWarnings("deprecation")
	@Override
	public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
		View v = convertView;

		if (v == null) {
			viewHolder = new ViewHolder();
			v = inflater.inflate(R.layout.row_setting_group, parent, false);
			viewHolder.tv_groupName = (TextView) v.findViewById(R.id.tv_settingcategory);
			viewHolder.iv_image = (ImageView) v.findViewById(R.id.iv_categoryicon);
			viewHolder.iv_indicateIcon = (ImageView) v.findViewById(R.id.iv_indicateopen);

			v.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) v.getTag();
		}

		if (isExpanded) {
			viewHolder.iv_indicateIcon.setImageResource(R.drawable.indicate_open);
		} else {
			viewHolder.iv_indicateIcon.setImageResource(R.drawable.indicate_close);
		}

		viewHolder.tv_groupName.setText(getGroup(groupPosition).getTitle());
		viewHolder.iv_image.setBackgroundDrawable(getGroup(groupPosition).getIcon());
		return v;
	}

	@Override
	public boolean hasStableIds() {
		return true;
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return true;
	}

	int getLayout(int childPosition) {
		int layoutId = 0;

		switch (childPosition) {
		case 0:
			layoutId = R.layout.row_setting_child_profile;
			break;
		case 1:
			layoutId = R.layout.row_setting_child_myplace;
			break;
		case 2:
			layoutId = R.layout.row_setting_child_info;
			break;
		}
		return layoutId;
	}

	class ViewHolder {
		public ImageView iv_image;
		public TextView tv_groupName;
		public ImageView iv_indicateIcon;
	}

	public class MStatusCallback implements Session.StatusCallback {
		@Override
		public void call(final Session session, SessionState state, Exception exception) {
			((SettingActivity_) context).setResult(Activity.RESULT_OK);
			if (session.isClosed()) {
				pref.clear();
				afterViews();
			} else {
				Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
					@Override
					public void onCompleted(GraphUser user, Response response) {
						if (user != null) {
							pref.fbAuthCode().put(session.getAccessToken());
							pref.collaboId().put(user.getId());
							pref.loginType().put("fb");
							pref.name().put(user.getName());
							getConnection();
							afterViews();
						}
					}
				});
				Request.executeBatchAsync(request);
			}
		}
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.btn_setLocation) {
			if (pref.usrId().get() == 0L) {
				showPleasLoginToast();
				return;
			}
			AlertDialog.Builder listBuilder = new AlertDialog.Builder(context);
			listBuilder.setTitle("지역구를 선택해 주세요.");
			listBuilder.setOnCancelListener(new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
				}
			});
			listBuilder.setItems(gu_locations, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {
					if (item == 0 && gu_locations.length == 26) {
						pref.location().remove();
						setLocationText("");
						notifyDataSetChanged();
						return;
					}
					pref.location().put(gu_locations[item]);
					setLocationText(pref.location().get());
					notifyDataSetChanged();
				}
			});
			AlertDialog alertList = listBuilder.create();
			alertList.show();
		}
	}

	private void setLocationText(String text) {
		aq.id(R.id.tv_child_myplace_text).text(text);
		mGroupList.get(1).setTitle(setGroupLoccationTitle());
	}

	private String setGroupLoccationTitle() {
		String setPlace = " 설정";
		if (pref.location().get().length() != 0) {
			setPlace = " : " + pref.location().get();
		}
		return my_place + setPlace;

	}

	@Background
	public void getConnection() {
		try {
			afterGetConnection(loginPost.sendJsonRequest());
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@UiThread
	public void afterGetConnection(JSONObject jo) {
		((LoginPost) loginPost).getAuthcode(jo);
	}

	private void showPleasLoginToast() {
		if (pleaseLoginToast == null) {
			pleaseLoginToast = Toast.makeText(context, context.getResources().getString(R.string.pleaseLogin),
					Toast.LENGTH_SHORT);
		}

		pleaseLoginToast.show();
	}
}
